var user = getCookie("lgc");
if (user) {
    $(".tips").html(`<a href="#">${user}</a> <span></span><div class="exit">退出</div>`).css({ fontFamily: "icomoon" });
    $(".tips").mouseenter(function () {
        $(".exit").css({ display: "block" });
    })
    $(".tips").mouseleave(function () {
        $(".exit").css({ display: "none" });
    })
}
$(".exit").click(function () {
    delCookie("lgc");
    location.reload();
})

$(".searchCon").focus(function () {
    $(".search").css({ display: "none" });
})
$(".searchCon").blur(function () {
    if ($(this).val().length > 0) {
        $(".search").css({ display: "none" });
    } else {
        $(".search").css({ display: "block" });
    }
})

$(".left").on("mouseenter", "li", function () {
    $(".po").animate({ left: $(this).index() * 123 }, 100);
})
$(".left").mouseleave(function () {
    $(".po").stop(true, true);
    $(".po").animate({ left: 0 }, 100);
})

shoppingCar();
async function shoppingCar() {
    var result = await shopCar({ user });
    var { status, msg, list, count } = result;
    $(".allCount").text(count);
    if (status) {
        var obj = list.values();
        var html = "";
        for (var val of obj) {
            var { gName, gImg, gPrice, gStore, id, gid, num } = val;
            var price = (gPrice * 1).toFixed(2);
            var total = (price * num).toFixed(2);
            html += `<div class="stroe">
                        <input type="checkbox" name="" id="" class="storeCheck">
                        <div class="storeIcon"></div>
                        <span>店铺 : </span>
                        <a href="javascript:;">${gStore}</a>
                    </div>
                    <div class="goods" data-id="${id}">
                        <div class="checkOneInp"><input type="checkbox" class="checkOne" name="" id=""></div>
                        <div class="goodsImg"><a href="javascript:;"><img src="${gImg}" alt=""></a></div>
                        <div class="goodsName"><a href="javascript:;">${gName}</a></div>
                        <ul class="goodsInfo">
                            <li>颜色</li>
                        </ul>
                        <div class="price">￥<span>${gPrice}</span></div>
                        <div class="goodsNum">
                            <div class="reduce">${num > 1 ? "-" : ""}</div>
                            <input type="text" class="counts" value = "${num}">
                            <div class="add">+</div>
                        </div>
                        <div class="subTotal">￥<span>${total}</span></div>
                        <div class="deleteBar"><span class="delete">删除</span></div>
                    </div>`;
        }
        $(".carGoods").html(html);

        $(".checkAll").click(function () {
            $(".storeCheck").prop("checked", $(this).prop("checked"));
            $(".checkOne").prop("checked", $(this).prop("checked"));
            $(".checkAll").prop("checked", $(this).prop("checked"));
            getTotal();
            totalHandler();
        })

        $(".checkOne").click(function () {
            $(this).parents(".goods").prev().children(".storeCheck").prop("checked", $(this).prop("checked"));
            isCheckAll();
            getTotal();
            totalHandler();
        })
        $(".storeCheck").click(function () {
            $(this).parents(".stroe").next().children().children(".checkOne").prop("checked", $(this).prop("checked"));
            isCheckAll();
            getTotal();
            totalHandler();
        })

        $(".add").click(async function () {
            var buyNum = $(this).prev().val();
            buyNum++;

            if (buyNum > 1) {
                $(this).prevAll(".reduce").text("-");
            }
            $(this).prev().val(buyNum);
            var id = $(this).parents(".goods").attr("data-id");
            var result = await updateShopCar({ id, buyNum });

            var price = $(this).parents(".goods").find(".price").children("span").text() * 1;
            var num = $(this).parents(".goods").find(".counts").val() * 1;
            $(this).parents(".goods").find(".subTotal").children("span").text((price * num).toFixed(2));
            getTotal();
        })
        $(".reduce").click(async function () {
            if ($(this).next().val() <= 1) return false;
            var buyNum = $(this).next().prop("value");
            buyNum--;
            if (buyNum == 1) {
                $(this).text("");
            }
            $(this).next().val(buyNum);
            var id = $(this).parents(".goods").attr("data-id");
            var result = await updateShopCar({ id, buyNum });
            var price = $(this).parents(".goods").find(".price").children("span").text() * 1;
            var num = $(this).parents(".goods").find(".counts").val() * 1;
            $(this).parents(".goods").find(".subTotal").children("span").text((price * num).toFixed(2));
            getTotal();
        })

        $(".delete").click(async function () {
            if (confirm("是否删除该商品")) {
                var id = $(this).parents(".goods").attr("data-id");
                var result = await deleteGoods({ id });
                $(this).parents(".goods").prev(".stroe").remove();
                $(this).parents(".goods").remove();
                isCheckAll();
                getTotal();
                totalHandler();
                changeCount();
            }
        })

        $(".deleteAll span").click(function () {
            if ($(this).parents(".settlementBar").prev().find(".checkOne").length > 0) {
                if ($(this).parents(".settlementBar").prev().find(".checkOne:checked").length > 0) {
                    if (confirm("是否删除选中商品")) {
                        $(this).parents(".settlementBar").prev().find(".checkOne:checked").each(async function () {
                            var ids = $(this).parents(".goods").attr("data-id");
                            var result = await deleteAllGoods({ ids });
                            console.log(result);
                        })

                        $(this).parents(".settlementBar").prev().find(".checkOne:checked").parents(".goods").prev().remove();
                        $(this).parents(".settlementBar").prev().find(".checkOne:checked").parents(".goods").remove();
                        isCheckAll();
                        getTotal();
                        totalHandler();
                        changeCount();
                    }
                } else {
                    alert("请至少选择一件商品")
                }
            } else {
                alert("请至少添加一件商品")
            }
        })
    }
}

function totalHandler() {
    var flag = false;
    $(".checkOne").each(function () {
        if ($(this).prop("checked")) {
            flag = true;
        }
    })
    if (flag) {
        $(".settlement").css({ backgroundColor: "#ff4400" });

        $(".settlement").click(function () {
            $(".shadow").css({ display: "block" });
            var timer = setInterval(function () {
                $(".one").slideDown("normal");
                setTimeout(function () {
                    $(".one").text("如果你坚持，我也不客气");
                    clearInterval(timer);
                }, 3000)
            }, 1000)
        })

        $(".title").on("click", "div", function () {
            $(this).addClass("active1").siblings().removeClass("active1");
            $(this).parents(".payment").find("img").eq($(this).index()).css({ display: "block" }).siblings().css({ display: "none" });
        })

        $(".close").click(function () {
            $(".shadow").css({ display: "none" });
        })

    } else {
        $(".settlement").css({ backgroundColor: "#aaaaaa" });
    }
}

function isCheckAll() {
    var flag = true;
    $(".checkOne").each(function () {
        if (!$(this).prop("checked")) {
            flag = false;
        }
    })
    var state = $(".checkOne").length > 0 ? flag : false;
    $(".checkAll").prop("checked", state);
}

function getTotal() {
    var sum = 0;
    var num = 0;
    $(".checkOne:checked").each(function () {
        num += $(this).parents(".goods").find(".counts").val() * 1;
        sum += $(this).parents(".goods").find(".subTotal").children("span").text() * 1;
    })
    $(".goodsCount").children("span").text(num);
    $(".total").text(sum.toFixed(2));
}

function changeCount() {
    var user = getCookie("lgc");
    change();
    async function change() {
        var result = await shopCar({ user });
        var { count } = result;

        $(".count").html(count);
        $(".allCount").html(count);
        if ($(".count").text() * 1 > 0) {
            $(".subNav li").html(`<a href="../html/shoppingCar.html" class="toCar">查看我的购物车</a>`);
        }
    }

}